/**
 * [一句话描述该类的功能]
 *
 * @author : [kai]
 * @version : [v1.0]
 * @createTime : [2022/10/28 15:35]
 */


package com.find.config;

import com.find.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURL=request.getRequestURI();
        log.info("preHandle Interceptor路径："+requestURL);
        //自动登录检查业务逻辑
        //获取cookie中的token，查询该token在服务器中是否存在，如果存在说明登录过，创建session对话，将对象塞入（不拦截）
        Cookie[] cookies=request.getCookies();
        String s=request.getHeader("Cookie");
        if(s!=null) {
            boolean uid = userService.logInStat(s);
            if (uid) {
                log.info("preHandle Interceptor 放行");
                return true;
            }
        }
        if(cookies!=null&&cookies.length!=0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("name")) {
                    String token = cookie.getValue();
                    if(s!=null&&s.equals((token))){
                        break;
                    }
                    log.warn(token);
                    System.out.println(token);
                    boolean uid = userService.logInStat(token);
                    if (uid) {
                        log.info("preHandle Interceptor 放行");
                        return true;
                    }
                }
            }
        }
        //拦截，跳转登录页
        log.info("preHandle Interceptor 拦截");
        request.setAttribute("msg","请先登录");
        response.setStatus(500);
        request.getRequestDispatcher("/login.html").forward(request,response);

        return false;
    }
}
